<?php

namespace App\Http\Controllers;

use App\MongoDBModels\PhotoUserFaces;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;


class PhotoUserFacesController extends Controller
{

    /**
     * @param Request $request
     * @return false|string
     * @desc 写入历史人脸数据
     */
    public function create(Request $request)
    {
        $params = $request->all();

        if (isset($params['user_id']) && isset($params['image_base64'])) {
            Log::info(json_encode($params));
            $params['md5'] = md5($params['image_base64']);
            $photo = PhotoUserFaces::query()->where('user_id', (int)$params['user_id'])->where('md5', $params['md5'])->where('type', (int)$params['type'])->first();
            if (empty($photo)) {
                $params['created_time'] = date("Y-m-d H:i:s", time());
                $params['updated_time'] = date("Y-m-d H:i:s", time());
                $result = PhotoUserFaces::query()->create($params); //写入数据
            } else {
                //代表绑定的照片，只能为一张
                if (2 == $params['type']) {
                    $params['updated_time'] = date("Y-m-d H:i:s", time());
                    $int = PhotoUserFaces::query()->where('_id', $photo->_id)->update($params); //写入数据
                }
            }
        }
        return $this->returnResponse(0, 'success', []);
    }

    /**
     * @return void
     * @desc 获取历史人脸检测数据
     */
    public function list(Request $request)
    {
        $params = $request->all();
        if (!isset($params['user_id'])) {
            return $this->returnResponse(400, '参数不能为空', []);
        }
        $photoList = PhotoUserFaces::query()->where('user_id', (int)$params['user_id'])->where('type', (int)$params['type'])->orderBy('created_at', 'desc')->limit(10)->get();
        if (count($photoList) > 0) {
            return $this->returnResponse(0, 'success', $photoList);
        }
        return $this->returnResponse(0, 'success', new \stdClass());
    }

    /**
     * @return void
     * @desc 单条记录
     */
    public function first(Request $request)
    {
        $params = $request->all();
        if (!isset($params['user_id'])) {
            return $this->returnResponse(400, '参数不能为空', []);
        }
        if (empty($params['md5'])) {
            return $this->returnResponse(400, '参数不能为空', []);
        }
        $query =  PhotoUserFaces::query()->where('md5',$params['md5']);
        $photoList =$query->where('user_id', (int)$params['user_id'])->where('type', 1)->first();
        return $this->returnResponse(0, 'success', $photoList);
    }
}
